//用户地址 projectwork
const router = require('koa-router')()

router.prefix('/userreceive')

//通过addressid获取用户地址
router.post('/addressid', async (ctx, next) => {
    let addressid = ctx.request.body.addressid;
    let result = await ctx.db.EXCUTE('SELECT * FROM userreceive WHERE addressid = ' + addressid);
    ctx.body = result;
})



//backend
//页面初始化时获取数据库内userreceive表的数据条目
router.post('/getuserreceivebackend', async (ctx, next) => {
    let sql0 = 'SELECT * FROM userreceive'
    let result = await ctx.db.EXCUTE(sql0);
  
    ctx.body = {
      code: 200,
      data: result
    };
  })

  router.post('/getmyaddress', async (ctx, next) => {
    let userid = ctx.request.body.userid;
    let sql = 'SELECT * FROM userreceive where userid=?'
    let result = await ctx.db.EXCUTE(sql,[userid]);
    ctx.body = {
      code: 200,
      data: result
    };
  })
  router.post('/updatedefault', async (ctx, next) => {
    let userid = ctx.request.body.userid;
    let addressid = ctx.request.body.addressid;
    console.log(addressid);
    let sql = 'update userreceive set isdefault = 0 where userid=?'
    let sql1 = ' update userreceive set isdefault=1 where userid=? and addressid=?'
    let result = await ctx.db.EXCUTE(sql,[userid]);
    let result1 = await ctx.db.EXCUTE(sql1,[userid, addressid]);
    ctx.body = {
      code: 200,
      data: result1
    };
  })
  router.post('/getdefault', async (ctx, next) => {
    let userid = ctx.request.body.userid;
    let sql = 'select * from userreceive where isdefault=1 and userid=?'
    let result = await ctx.db.EXCUTE(sql,[userid]);
    ctx.body = {
      code: 200,
      data: result
    };
  })

  router.post('/deladdress', async (ctx, next) => {
    let addressid = ctx.request.body.addressid;
    console.log(addressid);
    let sql = 'delete from userreceive where addressid=?'
    let result = await ctx.db.EXCUTE(sql,[addressid]);
    ctx.body = {
      code: 200
    //   data: result
    };
  })
  router.post('/addaddress', async (ctx, next) => {
    let userid = ctx.request.body.userid;
    let address = ctx.request.body.address;
    let phone = ctx.request.body.phone;
    let name = ctx.request.body.name;
    console.log(ctx.request.body);
    console.log(Number(phone));
    let sql = 'insert into userreceive(userid, address, phone, name, isdefault) values (?, ?, ?, ?, ?)'
    let result = await ctx.db.EXCUTE(sql,[userid, address, Number(phone), name, 0]);
    ctx.body = {
      code: 200
    //   data: result
    };
  })

module.exports = router